﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Cashier.utils
{
    public class DataItem
    {
        private String displayMember;
        private String valueMember;

        private DataItem(String displayMember, String valueMember)
        {
            this.displayMember = displayMember;
            this.valueMember = valueMember;
        }

        public String DisplayMember
        {
            get { return displayMember; }
            set { displayMember = value; }
        }

        public String ValueMember
        {
            get { return valueMember; }
            set { valueMember = value; }
        }

        /// <summary>
        /// 返回DataItem
        /// </summary>
        /// <param name="displayMember"></param>
        /// <param name="valueMember"></param>
        /// <returns></returns>
        public static DataItem GetDataItem(String displayMember, String valueMember)
        {
            return new DataItem(displayMember, valueMember);
        }

        /// <summary>
        /// 返回绑定项列表
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="displayMembers"></param>
        /// <param name="joinFormat"></param>
        /// <param name="valueMember"></param>
        /// <returns></returns>
        public static List<DataItem> GetDataItemList(DataTable dt, String displayMembers, String joinFormat, String valueMember)
        {
            List<DataItem> list = new List<DataItem>();
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    String[] displayArr = displayMembers.Split(new Char[] { ',' });
                    StringBuilder sb = new StringBuilder();
                    foreach (DataRow row in dt.Rows)
                    {
                        sb.Remove(0, sb.Length);
                        foreach (String display in displayArr)
                        {
                            sb.Append(row[display].ToString()).Append(joinFormat);
                        }
                        sb.Remove(sb.Length - joinFormat.Length, joinFormat.Length);
                        list.Add(new DataItem(sb.ToString(), row[valueMember].ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }
    }
}
